/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin		 	*/
/*	Project:	GlbLib-1.0.0			*/
/*	Author:		gong_libin			*/
/*	Date:		2016_06_01			*/
/*	File:		GlbCdLock.cpp			*/
/********************************************************/

#include "GlbCdLock.h"

namespace GlbCls
{

CGlbCdLock::CGlbCdLock()
{
}

CGlbCdLock::~CGlbCdLock()
{
}

int CGlbCdLock::GlbLockMalloc(void* pLock)
{
	if (NULL == CGlbLock::m_pLock) {
		CGlbLock::m_pLock = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t));
		if (NULL == CGlbLock::m_pLock) {
			return GLB_FAILURE;
		}
	}
	else {
		CGlbLock::m_pLock = (pthread_mutex_t*)pLock;
	}

	return GLB_SUCCESS;
}

int CGlbCdLock::GlbLockCreate(bool bShared)
{
	pthread_mutexattr_t stAttr;

	if (NULL != CGlbLock::m_pLock) {
		if (GLB_SUCCESS !=  pthread_mutexattr_init(&stAttr)) {
			GLB_ERROR("%s\n", strerror(errno));
			return GLB_FAILURE;
		}

		if (true == bShared) {
			if (GLB_SUCCESS != pthread_mutexattr_setpshared(&stAttr, PTHREAD_PROCESS_SHARED)) {
				GLB_ERROR("%s\n", strerror(errno));
				return GLB_FAILURE;
			}
		}

		if (GLB_SUCCESS != pthread_mutex_init((pthread_mutex_t*)CGlbLock::m_pLock, &stAttr)) {
			GLB_ERROR("%s\n", strerror(errno));
			return GLB_FAILURE;
		}

		if (GLB_SUCCESS != pthread_mutexattr_destroy(&stAttr)) {
			GLB_ERROR("%s\n", strerror(errno));
			return GLB_FAILURE;
		}

		if (GLB_SUCCESS != pthread_cond_init(&m_stCond, NULL)) {
			GLB_ERROR("%s\n", strerror(errno));
			return GLB_FAILURE;
		}
	}
	else {
		return GLB_FAILURE;
	}

	return GLB_SUCCESS;
}

int CGlbCdLock::GlbLockDelete()
{
	if (NULL != CGlbLock::m_pLock) {
		if (GLB_SUCCESS != pthread_mutex_destroy((pthread_mutex_t*)CGlbLock::m_pLock)) {
			GLB_ERROR("%s\n", strerror(errno));
			return GLB_FAILURE;
		}
		if (GLB_SUCCESS != pthread_cond_destroy(&m_stCond)) {
			GLB_ERROR("%s\n", strerror(errno));
			return GLB_FAILURE;
		}
	}

	return GLB_SUCCESS;
}

} /* GlbCls */
